package com.etoak.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hwpf.extractor.WordExtractor;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class WordUtils {
    /**
     * @Title: getTextFromWord
     * @Description: 读取word
     * @param filePath
     *            文件路径
     * @return: String 读出的Word的内容
     */
    public static String getTextFromWord(String filePath) {
        String result = null;
        File file = new File(filePath);
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            @SuppressWarnings("resource")
            WordExtractor wordExtractor = new WordExtractor(fis);
            result = wordExtractor.getText();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * 匹配两个文件的差异，主要输出新文件与旧文件的差异，并输出
     * @param oldFile 旧的文件
     * @param newFile 当前新文件
     * @throws IOException 异常
     */
    public static void compareTwoFile(String oldFile, String newFile) throws IOException {
        List<String> list1 =  Files.readAllLines(Paths.get(oldFile));
        List<String> list2 =  Files.readAllLines(Paths.get(newFile));

        log.info("比较{}和{}两个文件，以 {} 为主", oldFile, newFile, newFile);
        List<String> finalList = list2.stream().filter(line ->
                list1.stream().filter(line2 -> line2.equals(line)).count() == 0
        ).collect(Collectors.toList());
        if (finalList.size() == 0) {
            log.info("两个文件无差异");
        }else{
            log.info("以下为差异的地方：");
            finalList.forEach(one -> System.out.println(one));
        }
    }

}
